var express = require('express'),
  util = require('util'),
  bodyParser = require('body-parser'),
  multer = require('multer'),
  fs = require('fs'),
  cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());

// 处理静态文件,访问地址不需要加上public
// 如；localhost:8888/images/test.png
app.use(express.static('statics'));

/**
 * get和post
 */
app.get('/toGet', function(req, res) {
  res.sendFile(__dirname + "/templates/" + "get.html");
});

app.get('/toPost', function(req, res) {
  res.sendFile(__dirname + "/templates/" + "post.html");
});

// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.post('/process_post', urlencodedParser, function(req, res) {
  var response = {
    first_name: req.body.first_name,
    last_name: req.body.last_name
  };
  console.log(response);
  res.end(JSON.stringify(response));
});

app.get('/process_get', function(req, res) {
  console.log("Cookies: ", req.cookies);
  var response = {
    first_name: req.query.first_name,
    last_name: req.query.last_name
  };
  console.log(response);
  res.end(JSON.stringify(response));
});

/**
 * 文件上传
 */

// 临时存储地址
app.use(multer({ dest: __dirname + '/tmp/' }).array('image'));
app.get('/toUpload', function(req, res) {
  res.sendFile(__dirname + '/templates/' + 'upload.html');
});

app.post('/file_upload', function(req, res) {
  console.log(req.files[0]); // 上传的文件信息
  var des_file = __dirname + "/files/" + req.files[0].originalname;
  fs.readFile(req.files[0].path, function(err, data) {
    fs.writeFile(des_file, data, function(err) {
      if (err) {
        console.log(err);
      } else {
        response = {
          message: 'File uploaded successfully',
          filename: req.files[0].originalname
        };
      }
      console.log(response);
      res.end(JSON.stringify(response));
      // 使用子进程删除缓存文件
      require('child_process').exec('rm -rf tmp', function(err, out) {
        console.log(out);
        if (err) { console.log(err); }
      });
    });
  });
});

app.get('/request', function(req, res) {
  console.log('req.baseUrl:' + req.baseUrl);
  console.log('req.body:' + req.body);
  console.log('req.cookie:' + req.cookie);
  console.log('req.hostname:' + req.hostname);
  console.log('req.ip:' + req.ip);
  console.log('req.originalUrl:' + req.originalUrl);
  console.log('req.params:' + util.inspect(req.params));
  console.log('req.path:' + req.path);
  console.log('req.protocal:' + req.protocal);
  console.log('req.path:' + req.path);
  console.log('req.query:' + util.inspect(req.query));
  console.log('req.route:' + util.inspect(req.route));
  console.log('req.subdomains:' + req.subdomains);
  res.send('Hello World!');
});

var server = app.listen(8888, function() {
  var host = server.address().address;
  var port = server.address().port;
  console.info('应用实例，访问地址：%s:%s', host, port);
});
